package internal

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"syscall"
	"time"
)

func absPath(str string) (string, error) {
	p, err := filepath.Abs(fmt.Sprintf("data/%v", str))
	if err != nil {
		return "", err
	}
	return p, pathExists(p)
}

// RunBrowser run a browser
func RunBrowser() (string, error) {
	name := "/bin/bash"
	args := []string{"-c"}
	if runtime.GOOS == "windows" {
		name = "cmd"
		args = []string{"/c"}
	}
	dataDir, err := absPath("browser")
	if err != nil {
		return "", err
	}
	browserPath := "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
	port := 29999
	args = append(
		args,
		browserPath,
		fmt.Sprintf("--remote-debugging-port=%v", port),
		fmt.Sprintf("--user-data-dir=%v", dataDir),
	)
	cmd := exec.Command(name, args...)
	if runtime.GOOS == "windows" {
		cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	}
	if err := cmd.Start(); err != nil {
		return "", err
	}
	go cmd.Wait()
	var wsUri string
	for {
		time.Sleep(100 * time.Millisecond)
		version, err := getBrowserWSEndpoint(port)
		if err != nil {
			continue
		}
		wsUri = version.WebSocketDebuggerUrl
		break
	}
	return wsUri, nil
}

func getBrowserWSEndpoint(port int) (BrowserVersion, error) {
	var version BrowserVersion
	response, err := http.Get(fmt.Sprintf("http://localhost:%v/json/version", port))
	if err != nil {
		return version, err
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		return version, err
	}
	if err := json.Unmarshal(body, &version); err != nil {
		return version, err
	}
	return version, nil
}
func pathExists(path string) error {
	_, err := os.Stat(path)
	if err == nil {
		return nil
	}
	if os.IsNotExist(err) {
		err := os.MkdirAll(path, os.ModePerm)
		if err != nil {
			return err
		} else {
			return nil
		}
	}
	return err
}
